﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Caching;
using System.IO;
using System.Text;
using System.Web.WebPages;

namespace Commons.Web
{
    /// <summary>
    /// 缓存的扩展方法
    /// </summary>
    public static class CacheExtensions
    {
        /// <summary>
        /// 对页面中指定字符串进行缓存
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="cacheKey">缓存Key</param>
        /// <param name="cacheDependencies">缓存依附对象，可以为null</param>
        /// <param name="absoluteExpiration">过期时间</param>
        /// <param name="slidingExpiration">相对本次过期时间</param>
        /// <param name="func">要缓存对象</param>
        /// <returns></returns>
        public static HelperResult Cache(this HtmlHelper htmlHelper, string cacheKey, CacheDependency cacheDependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, Func<object, HelperResult> func)
        {
            var cache = htmlHelper.ViewContext.HttpContext.Cache;
            var content = cache.Get(cacheKey) as string;

            if (content == null)
            {
                content = func.Invoke(null).ToHtmlString();
                cache.Insert(cacheKey, content, cacheDependencies, absoluteExpiration, slidingExpiration);
            }

            return new HelperResult(writer =>
            {
                writer.Write(content);
            });
        }

        /// <summary>
        /// 对页面中指定字符串进行缓存
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="cacheKey">缓存Key</param>
        /// <param name="absoluteExpiration">过期时间</param>
        /// <param name="slidingExpiration">相对本次的过期时间</param>
        /// <param name="func">要缓存对象</param>
        /// <returns></returns>
        public static HelperResult Cache(this HtmlHelper htmlHelper, string cacheKey, DateTime absoluteExpiration, TimeSpan slidingExpiration, Func<object, HelperResult> func)
        {
            return Cache(htmlHelper, cacheKey, null, absoluteExpiration, slidingExpiration, func);
        }

        /// <summary>
        /// 对页面中指定字符串进行缓存
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="cacheKey">缓存Key</param>
        /// <param name="absoluteExpiration">过期时间</param>
        /// <param name="func">要缓存对象</param>
        /// <returns></returns>
        public static HelperResult Cache(this HtmlHelper htmlHelper, string cacheKey, DateTime absoluteExpiration, Func<object, HelperResult> func)
        {
            return Cache(htmlHelper, cacheKey, null, absoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, func);
        }
    }
}